package com.m1905.lib.download.sample;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.m1905.lib.download.DownloadManager;
import com.m1905.lib.download.listener.DownloadStatusListener;
import com.m1905.lib.download.listener.OnCmdCompletedListener;
import com.m1905.lib.download.model.DownloadDBItem;
import com.m1905.lib.download.model.State;
import com.m1905.lib.download.util.DLog;

import java.util.List;

/**
 * @author wanghao
 * @date 2023/10/12.
 * @des
 */
public class DownloadManagerListActivity extends Activity implements DownloadStatusListener {

    private RecyclerView mRecyclerView;
    private DownloadManagerAdapter mAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download_manager_list);
        mRecyclerView = findViewById(R.id.rv);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new DownloadManagerAdapter();
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        mAdapter.setData(DownloadManager.getInstance().getDownloadList());
        DownloadManager.getInstance().registerDownloadStatusListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DownloadManager.getInstance().unregisterDownloadStatusListener(this);
    }

    @Override
    public void onWaiting(DownloadDBItem downloadItem, boolean insert) {
        mAdapter.setData(DownloadManager.getInstance().getDownloadList());
    }

    @Override
    public void onStart(DownloadDBItem downloadItem) {
        mAdapter.updateItem(downloadItem);
    }

    @Override
    public void onFileSize(DownloadDBItem downloadItem) {
        mAdapter.updateItem(downloadItem);
    }

    @Override
    public void onLoading(DownloadDBItem downloadItem) {
        mAdapter.updateItem(downloadItem);
    }

    @Override
    public void onSuccess(DownloadDBItem downloadItem) {
        mAdapter.updateItem(downloadItem);
    }

    @Override
    public void onFailure(DownloadDBItem downloadItem) {
        mAdapter.updateItem(downloadItem);
    }

    @Override
    public void onCancel(DownloadDBItem downloadItem) {
        mAdapter.updateItem(downloadItem);
    }

    @Override
    public void onDelete(DownloadDBItem downloadItem) {
        mAdapter.deleteItem(downloadItem);
    }

    @Override
    public void onCmdComplete(int status) {

    }

    private static class DownloadManagerAdapter extends RecyclerView.Adapter<ItemViewHolder> implements View.OnClickListener, View.OnLongClickListener {

        private List<DownloadDBItem> mData;

        public void setData(List<DownloadDBItem> mData) {
            this.mData = mData;
            notifyDataSetChanged();
        }

        @NonNull
        @Override
        public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_download_manager_list, parent, false);
            view.setOnClickListener(this);
            view.setOnLongClickListener(this);
            return new ItemViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull ItemViewHolder holder, int position) {
            holder.itemView.setTag(position);
            DownloadDBItem item = mData.get(position);
            holder.mTitle.setText(item.getId() + " -> " + item.getTitle() + "   " + item.getState());
            holder.mDesc.setText(item.getState() + " DownloadSize:" + item.getDownloadSize() + "  TotalSize:" + item.getTotalSize() + "  progress:" + progress(item.getDownloadSize(), item.getTotalSize()) + "   speed:" + item.getDownloadSpeed());
        }

        @Override
        public int getItemCount() {
            return mData != null ? mData.size() : 0;
        }

        private String progress(long current, long total) {
            if (total > 0) {
                return (int) (current * 100 / total) + "%";
            }
            return "未知";
        }

        public void updateItem(DownloadDBItem target) {
            DLog.e("DownloadManagerListActivity updateItem " + target);
            for (int i = 0; i < mData.size(); i++) {
                DownloadDBItem item = mData.get(i);
                if (target.getId() == item.getId()) {
                    item.readFrom(target);
                    notifyItemChanged(i, 0);
                    DLog.e("DownloadManagerListActivity updateItem find item " + i + target + System.identityHashCode(target));
                    DLog.e("DownloadManagerListActivity updateItem find item " + i + item + System.identityHashCode(item));
                    return;
                }
            }
            DLog.e("DownloadManagerListActivity updateItem not find item ");
        }

        @Override
        public void onClick(View v) {
            int position = (int) v.getTag();
            DownloadDBItem item = mData.get(position);
            DLog.e("DownloadManagerListActivity onClick " + item);
            switch (item.getState()) {
                case State.WAITING:
                    DownloadManager.getInstance().stopDownload(item, new OnCmdCompletedListener() {
                        @Override
                        public void onCmdCompleted() {
                            DLog.e("onCompleted");
                        }
                    });
                    break;
                case State.STARTED:
                    DownloadManager.getInstance().stopDownload(item, new OnCmdCompletedListener() {
                        @Override
                        public void onCmdCompleted() {
                            DLog.e("onCompleted");
                        }
                    });
                    break;
                case State.LOADING:
                    DownloadManager.getInstance().stopDownload(item, new OnCmdCompletedListener() {
                        @Override
                        public void onCmdCompleted() {
                            DLog.e("onCompleted");
                        }
                    });
                    break;
                case State.FAILURE:
                    DownloadManager.getInstance().startDownload(item, new OnCmdCompletedListener() {
                        @Override
                        public void onCmdCompleted() {
                            DLog.e("onCompleted");
                        }
                    });
                    break;
                case State.CANCELLED:
                    DownloadManager.getInstance().startDownload(item, new OnCmdCompletedListener() {
                        @Override
                        public void onCmdCompleted() {
                            DLog.e("onCompleted");
                        }
                    });
                    break;
                case State.SUCCESS:
                    DownloadManager.getInstance().startDownload(item, new OnCmdCompletedListener() {
                        @Override
                        public void onCmdCompleted() {
                            DLog.e("onCmdCompleted");
                        }
                    });
                    break;
            }
        }

        @Override
        public boolean onLongClick(View v) {
            int position = (int) v.getTag();
            DownloadDBItem item = mData.get(position);
            DLog.e("DownloadManagerListActivity onLongClick " + item);
            switch (item.getState()) {
                case State.WAITING:
                    DownloadManager.getInstance().deleteDownload(item, new OnCmdCompletedListener() {
                        @Override
                        public void onCmdCompleted() {
                            DLog.e("onCompleted ddd");
                        }
                    });
                    break;
                case State.STARTED:
                    DownloadManager.getInstance().deleteDownload(item, new OnCmdCompletedListener() {
                        @Override
                        public void onCmdCompleted() {
                            DLog.e("onCompleted ddd");
                        }
                    });
                    break;
                case State.LOADING:
                    DownloadManager.getInstance().deleteDownload(item, new OnCmdCompletedListener() {
                        @Override
                        public void onCmdCompleted() {
                            DLog.e("onCompleted ddd");
                        }
                    });
                    break;
                case State.FAILURE:
                    DownloadManager.getInstance().deleteDownload(item, new OnCmdCompletedListener() {
                        @Override
                        public void onCmdCompleted() {
                            DLog.e("onCompleted ddd");
                        }
                    });
                    break;
                case State.CANCELLED:
                    DownloadManager.getInstance().deleteDownload(item, new OnCmdCompletedListener() {
                        @Override
                        public void onCmdCompleted() {
                            DLog.e("onCompleted ddd");
                        }
                    });
                    break;
                case State.SUCCESS:
                    DownloadManager.getInstance().deleteDownload(item, new OnCmdCompletedListener() {
                        @Override
                        public void onCmdCompleted() {
                            DLog.e("onCompleted ddd");
                        }
                    });
                    break;
            }
            return true;
        }

        public void deleteItem(DownloadDBItem target) {
            for (int i = 0; i < mData.size(); i++) {
                DownloadDBItem item = mData.get(i);
                if (target.getId() == item.getId()) {
                    mData.remove(i);
                    DLog.e("deleteItem pos:" + i + "   " + target);
                    notifyItemRemoved(i);
                    break;
                }
            }

        }
    }

    private static class ItemViewHolder extends RecyclerView.ViewHolder {

        private TextView mTitle;
        private TextView mDesc;

        public ItemViewHolder(@NonNull View itemView) {
            super(itemView);
            mTitle = itemView.findViewById(R.id.title);
            mDesc = itemView.findViewById(R.id.desc);
        }
    }


}
